package com.bookmanagement.service;

import com.bookmanagement.entity.Book;
import com.bookmanagement.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service // 注解标识这是业务逻辑层组件，Spring会自动管理其生命周期
public class BookService {

    @Autowired // 自动注入BookMapper实例，无需手动创建，实现依赖解耦
    private BookMapper bookMapper;

    @Cacheable(value = "bookCache", key = "#id") // 缓存结果：将查询结果存入名为"bookCache"的缓存，键为图书ID
    public Book findById(Long id) {
        Book book = bookMapper.findById(id); // 调用mapper层查询数据库
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        return book;
    }

    public Book findByIsbn(String isbn) {
        return bookMapper.findByIsbn(isbn);
    }

    public List<Book> findBooksByCriteria(String title, String author, String isbn) {
        return bookMapper.findBooksByCriteria(title, author, isbn);
    }

    public Map<String, Object> getBooks(int pageNum, int pageSize, String title) {
        int offset = Math.max((pageNum - 1) * pageSize, 0);
        Map<String, Object> result = new HashMap<>();
        result.put("items", bookMapper.findBooks(title, offset, pageSize));
        result.put("total", bookMapper.countBooks(title));
        return result;
    }//通过@Service注解被 Spring 识别为业务组件，通过@Autowired注入BookMapper，实现对数据库的操作调用。

    @CacheEvict(value = "bookCache", allEntries = true)// 清除缓存：新增图书后清空bookCache，避免缓存脏数据
    public void createBook(Book book) { // 业务校验：ISBN已存在则抛异常（ISBN唯一）
        if (bookMapper.findByIsbn(book.getIsbn()) != null) {
            throw new RuntimeException("ISBN 已存在");
        } // 设置默认值：状态为"可借"，创建时间和更新时间为当前时间
        book.setStatus("AVAILABLE");
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.insertBook(book);
    }

    @CacheEvict(value = "bookCache", allEntries = true)
    public void updateBook(Book book) {
        Book existingBook = findById(book.getId());
        if (!existingBook.getIsbn().equals(book.getIsbn()) && bookMapper.findByIsbn(book.getIsbn()) != null) {
            throw new RuntimeException("ISBN 已存在");
        }
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.updateBook(book);
    }

    @CacheEvict(value = "bookCache", allEntries = true)
    public void deleteBook(Long id) {
        findById(id); // 确保图书存在
        if (bookMapper.checkBorrowing(id) > 0) {
            throw new RuntimeException("图书正在被借阅，无法删除");
        }
        bookMapper.deleteBook(id);
    }

    public Map<String, Object> getBookStatusStats() {
        List<Map<String, Object>> stats = bookMapper.countBooksByStatus();
        List<String> labels = stats.stream()
                .map(s -> "AVAILABLE".equals(s.get("status").toString()) ? "可借" : "已借")
                .toList();
        List<Long> values = stats.stream().map(s -> (Long) s.get("count")).toList();
        Map<String, Object> result = new HashMap<>();
        result.put("labels", labels);
        result.put("values", values);
        return result;
    }
}